/*
 * JaCoLiB
 * Copyright (C) 2008 Alessandro Serra
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package it.gashale.jacolib.json;

import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import it.gashale.jacolib.core.JacolibError;
import it.gashale.jacolib.core.ProtocolError;
import it.gashale.jacolib.json.object.*;
import it.gashale.jacolib.json.serializer.ObjectDeserializer;
import it.gashale.jacolib.json.serializer.ObjectSerializer;
import it.gashale.jacolib.json.serializer.SerializationObjectDeserializer;
import it.gashale.jacolib.json.serializer.SerializationObjectSerializer;
import it.gashale.jacolib.rpc.RPCRequest;
import it.gashale.jacolib.rpc.RPCResponse;

public class Serializer {
	private Hashtable<Class,ObjectSerializer> m_serializers;
	private Hashtable<String,ObjectDeserializer> m_deserializers;

	public Serializer() {
		m_serializers=new Hashtable<Class,ObjectSerializer>();
		m_deserializers=new Hashtable<String,ObjectDeserializer>();
		init();
	}
	
	public void register(Class cls, ObjectSerializer conv) {
		m_serializers.put(cls, conv);
	}
	public void register(String type, ObjectDeserializer conv) {
		m_deserializers.put(type, conv);
	}
	public void register(String type, Class cls) {
		m_serializers.put(cls, new SerializationObjectSerializer());
		m_deserializers.put(type, new SerializationObjectDeserializer(cls));
	}
	
	
	public Object decode(Reader reader) throws ProtocolError {
		Object obj=null;
		try {
			//System.out.println("Decoding...");
			JSONTokener to=new JSONTokener(reader);
			JSONObject jsonobj= new JSONObject(to);
			//System.out.println("To Decode: "+jsonobj.toString(2));
			obj=json_to_object(jsonobj);
		} catch (JSONException e) {
			new ProtocolError("Serialization error: "+e.getMessage());
		} catch (IOException e) {
			new ProtocolError("Serialization error: "+e.getMessage());
		}
		return obj;
	}
	
	public Object decode(String str) throws ProtocolError {
		return decode(new StringReader(str));
	}
	public String encode(Object o) throws JacolibError {
		Object jsonobj=null;
		String res=null;
		try {
			//System.out.println("Encoding... "+o.toString());
			jsonobj=object_to_json(o);
			res=jsonobj.toString();
			//System.out.println("Enecoded: "+res);
		} catch (JSONException e) {
			throw new JacolibError("Serialization error: "+e.getMessage());
		} catch (IOException e) {
			throw new JacolibError("Serialization error: "+e.getMessage());
		}
		return res;
	}
	public void encode(Object o, PrintStream strm) throws ProtocolError {
		Object jsonobj=null;
		try {
			jsonobj=object_to_json(o);
			//System.out.println("Encoded as: "+jsonobj.toString());
			strm.print(jsonobj.toString());
		} catch (JSONException e) {
			new InternalError("Serialization error: "+e.getMessage());
		} catch (IOException e) {
			new InternalError("Serialization error: "+e.getMessage());
		}
	}

	
	protected Object json_to_object(JSONObject jsonobj, String typename) throws JSONException, ProtocolError, IOException {
		ObjectDeserializer ser=(ObjectDeserializer)m_deserializers.get(typename);	
		if(ser==null) {
			throw new InternalError("Serialization Error: "+typename);
		}
		Object obj=null;
		obj=ser.read(this,jsonobj);
		return obj;
	}
	
	public Object json_to_object(JSONObject jsonobj) throws JSONException, ProtocolError, IOException {
		Object obj=null;
		String typename=(String)jsonobj.opt("type");
		if(typename==null || typename.equals("object.json")) {
			obj=jsonobj;
		} else {
			obj=json_to_object(jsonobj,typename);
		}
		return obj;
	}
	
	public Object object_to_json(Object obj) throws IOException, JSONException {
		Object jobj=null;
		
		if(obj!=null) {
			ObjectSerializer ser=(ObjectSerializer)m_serializers.get(obj.getClass());
			if(ser!=null) {
				JSONObject jsonobj=new JSONObject();
				ser.write(this,obj,jsonobj);
				jobj=jsonobj;
			} else if(JSONObject.class.isInstance(obj)) {
				jobj=obj;
			} else if(	String.class.isInstance(obj) ||
						Integer.class.isInstance(obj) ||
						Float.class.isInstance(obj) ||
						Double.class.isInstance(obj) ||
						Boolean.class.isInstance(obj)) {
				jobj=obj;
			} else if (Collection.class.isInstance(obj)) {
				Collection c=(Collection)obj;
				JSONArray a=new JSONArray();
				Iterator it=c.iterator();
				while(it.hasNext()) {
					a.put(object_to_json(it.next()));
				}
				jobj=a;
			} else {
				jobj=object_to_json(new UnknowObject(obj));
			}	
		}
		return jobj;
	}
	
	protected void init() {
		register("object.unknow",UnknowObject.class);
		register("rpc.request",RPCRequest.class);
		register("rpc.response",RPCResponse.class);
	}
}
